package com.vivo.tasks.vivofx;

import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.excel.annotation.ExcelField;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.vivo.common.DatabaseContextHolder;
import com.vivo.dealer.entity.*;
import com.vivo.dealer.service.*;
import com.vivo.fx.dealer.entity.FxAreainfo;
import com.vivo.fx.dealer.entity.FxDealerinfo;
import com.vivo.fx.dealer.entity.FxDealerrelation;
import com.vivo.fx.dealer.entity.FxWarehouseinfo;
import com.vivo.fx.dealer.service.FxAreainfoService;
import com.vivo.fx.dealer.service.FxDealerinfoService;
import com.vivo.fx.dealer.service.FxDealerrelationService;
import com.vivo.fx.dealer.service.FxWarehouseinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class TaskViDealer {
    @Autowired
    private FxDealerinfoService fxDealerinfoService;

    @Autowired
    private ViDealerInfoService viDealerInfoService;

    @Autowired
    private FxAreainfoService fxAreainfoService;

    @Autowired
    private FxDealerrelationService fxDealerrelationService;

    @Autowired
    private VivoAreaService vivoAreaService;

    @Autowired
    private VivoDealerRelationService vivoDealerRelationService;

    public void SyncData() {
        // 同步经销商信息
        GetDealer("ah");
        GetDealer("js");

        // 同步代理商信息
        SyncTerminal();
    }



    public void SyncAreaInfo() {
        GetAreaInfo("ah");
        GetAreaInfo("js");
    }


    public void SyncDealerRelation() {
        GetDealerRelation("ah");
        GetDealerRelation("js");
    }


    public void SyncAgenter() {
        getAgenterInfo("ah");
        getAgenterInfo("js");
    }

    public void SyncTerminal() {
        getAgenterTerminal("ah");
        getAgenterTerminal("js");
    }


    private void GetDealer(String area) {
        System.out.println("get data from " + area + " db start...");

        int pageStart = 1;
        int pageSize = 15000;

        Page<FxDealerinfo> page = new Page<FxDealerinfo>(pageStart, pageSize);
        FxDealerinfo fxDealerinfo = new FxDealerinfo();

        try {
            // 删除所有数据
            ViDealerInfo vdi = new ViDealerInfo();
            vdi.setTableZone(area);
            viDealerInfoService.deleteAll(vdi);

            // 切换数据库
            Helper.changeDB(area);
            Page<FxDealerinfo> pageRes = fxDealerinfoService.findPage(page, fxDealerinfo);
            DatabaseContextHolder.setMainDb();

            SaveDealer(pageRes.getList(), area);
            for (int i = pageStart + 1; i <= pageRes.getTotalPage(); i++) {
                System.out.println("cur page is :" + pageRes.getPageNo() + " and pageSize is :" + pageRes.getPageSize());

                page.setPageNo(i);

                Helper.changeDB(area);
                pageRes = fxDealerinfoService.findPage(page, fxDealerinfo);
                DatabaseContextHolder.setMainDb();

                // 保存数据
                SaveDealer(pageRes.getList(), area);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            DatabaseContextHolder.setMainDb();
        }

        System.out.println("get data from " + area + " db end.");
    }


    private void SaveDealer(List<FxDealerinfo> dealerinfos, String area) {
        List<ViDealerInfo> dealerInfoList = new ArrayList<ViDealerInfo>();
        Office company = new Office();
        VivoArea vArea = new VivoArea();
        Date timeNow = new Date();

        for (FxDealerinfo fdi: dealerinfos) {
            ViDealerInfo vd = new ViDealerInfo();
            vd.setTableZone(area);
            vd.setDealerid(fdi.getDealerid());
            vd.setId(IdGen.uuid());
            vd.setUpdateDate(timeNow);
            vd.setCreateDate(timeNow);

            company.setId(fdi.getCompanyid());
            vd.setCompany(company);

            vArea.setId(fdi.getAreaid());
            vd.setArea(vArea);


            vd.setCreatetime(fdi.getCreatetime());
            vd.setDealercode(fdi.getDealercode());
            vd.setDealername(fdi.getDealername());
            vd.setDealernamepinying(fdi.getDealernamepinying());
            vd.setDealertype(fdi.getDealertype());
            vd.setDealeraddress(fdi.getDealeraddress());

            vd.setDealertelephone(fdi.getDealertelephone());
            vd.setIsentitydealer(fdi.getIsentitydealer());
            vd.setIswares(fdi.getIswares());
            vd.setIsmaterial(fdi.getIsmaterial());
            vd.setMarketlevelid(fdi.getMarketlevelid());
            vd.setTerminaltype(fdi.getTerminaltype());
            vd.setTerminallevelid(fdi.getTerminallevelid());
            vd.setDealerlevelid(fdi.getDealerlevelid());
            vd.setBysystemid(fdi.getBysystemid());
            vd.setClienttypeid(fdi.getClienttypeid());

            vd.setDitchtypeid(fdi.getDitchtypeid());
            vd.setTerminalbelongid(fdi.getTerminalbelongid());
            vd.setTerminalstate(fdi.getTerminalstate());
            vd.setAgentlevelid(fdi.getAgentlevelid());
            vd.setArelinkman(fdi.getArelinkman());
            vd.setArealinkmantelephone(fdi.getArealinkmantelephone());
            vd.setFinancelinkman(fdi.getFinancelinkman());
            vd.setFinancelinkmantelephone(fdi.getFinancelinkmantelephone());
            vd.setStorekeeper(fdi.getStorekeeper());
            vd.setStorekeepertel(fdi.getStorekeepertel());

            vd.setMagorbrand(fdi.getMagorbrand());
            vd.setBusiness(fdi.getBusiness());
            vd.setSelfstorecount(fdi.getSelfstorecount());
            vd.setTerminalcontacter(fdi.getTerminalcontacter());
            vd.setTerminalcontactertel(fdi.getTerminalcontactertel());
            vd.setTerminalshopkeeper(fdi.getTerminalshopkeeper());
            vd.setShopkeepertel(fdi.getShopkeepertel());
            vd.setTerminalstorekeeper(fdi.getTerminalstorekeeper());
            vd.setTerminalstorekeepertel(fdi.getTerminalstorekeepertel());
            vd.setTerminalmajorbrand(fdi.getTerminalmajorbrand());

            vd.setJointype(fdi.getJointype());
            vd.setServicetel(fdi.getServicetel());
            vd.setSalesscope(fdi.getSalesscope());
            vd.setTerminalarea(fdi.getTerminalarea());
            vd.setStartrundate(fdi.getStartrundate());
            vd.setRunyears(fdi.getRunyears());
            vd.setShopassistantcount(fdi.getShopassistantcount());
            vd.setPromotionscount(fdi.getPromotionscount());
            vd.setBrandservicecenter(fdi.getBrandservicecenter());
            vd.setAssetsconditions(fdi.getAssetsconditions());

            vd.setBarcount(fdi.getBarcount());
            vd.setBusinesslevelid(fdi.getBusinesslevelid());
            vd.setForeignenvid(fdi.getForeignenvid());
            vd.setHasspecarea(fdi.getHasspecarea());
            vd.setTerminalmaintainid(fdi.getTerminalmaintainid());
            vd.setSpecialareacount(fdi.getSpecialareacount());
            vd.setTerminalspecinfo(fdi.getTerminalspecinfo());


            vd.setIsspotcheck(fdi.getIsspotcheck());
            vd.setIshassaler(fdi.getIshassaler());
            vd.setDealerclientkindid(fdi.getDealerclientkindid());
            vd.setClientadminer(fdi.getClientadminer());
            vd.setClientadminertel(fdi.getClientadminertel());
            vd.setOrderadminer(fdi.getOrderadminer());
            vd.setClientadminertel(fdi.getClientadminertel());
            vd.setMarketadminer(fdi.getMarketadminer());
            vd.setMarketadminertel(fdi.getMarketadminertel());

            vd.setStanderpercent(fdi.getStanderpercent());
            vd.setPromotionsconfig(fdi.getPromotionsconfig());
            vd.setShvalue(fdi.getShvalue());
            vd.setIsstore(fdi.getIsstore());
            vd.setIsmakebill(fdi.getIsmakebill());
            vd.setMakebilltime(fdi.getMakebilltime());
            vd.setStoretype(fdi.getStoretype());
            vd.setLogisticsday(fdi.getLogisticsday());
            vd.setStorekind(fdi.getStorekind());
            vd.setLockgpsposition(fdi.getLockgpsposition());

            vd.setAgentcontracttypeid(fdi.getAgentcontracttypeid());
            vd.setIsself(fdi.getIsself());
            vd.setWechatno(fdi.getWechatno());
            vd.setEnableallotupretail(fdi.getEnableallotupretail());
            vd.setWebsite(fdi.getWebsite());
            vd.setFax(fdi.getFax());
            vd.setPOBox(fdi.getPOBox());
            vd.setTongbuimssystemresult(fdi.getTongbuimssystemresult());
            vd.setTongbuimssystemresultmessage(fdi.getTongbuimssystemresultmessage());
            vd.setImagetypeid(fdi.getImagetypeid());

            vd.setFactorymobiletypeid(fdi.getFactorymobiletypeid());
            vd.setStoreclassid(fdi.getStoreclassid());
            vd.setBusinessmodeid(fdi.getBusinessmodeid());
            vd.setServicetelephone(fdi.getServicetelephone());
            vd.setIsupcompanysite(fdi.getIsupcompanysite());
            vd.setStorecoordinate(fdi.getStorecoordinate());
            vd.setStoreemail(fdi.getStoreemail());
            vd.setSummerworktime(fdi.getSummerworktime());
            vd.setWinterworktime(fdi.getWinterworktime());
            vd.setNearbusstation(fdi.getNearbusstation());

            vd.setNearmetrostation(fdi.getNearmetrostation());
            vd.setBusinessrangeid(fdi.getBusinessrangeid());
            vd.setSalespropertyid(fdi.getSalespropertyid());
            vd.setFactoryareaid(fdi.getFactoryareaid());
            vd.setPricesystemid(fdi.getPricesystemid());
            vd.setSettlementunitid(fdi.getSettlementunitid());
            vd.setRetailvouchertype(fdi.getRetailvouchertype());
            vd.setUnicomcode(fdi.getUnicomcode());
            vd.setTelecomcode(fdi.getTelecomcode());
            vd.setMobilecode(fdi.getMobilecode());

            vd.setAdditionalcode1(fdi.getAdditionalcode1());
            vd.setBelongclientid(fdi.getBelongclientid());
            vd.setFinancialareacode(fdi.getFinancialareacode());
            vd.setIsfinancialaccount(fdi.getIsfinancialaccount());

            dealerInfoList.add(vd);

            if (dealerInfoList.size() >= 1000) {
                SaveDealerList(dealerInfoList, area);

                dealerInfoList.clear();
            }
        }

        if (dealerInfoList.size() > 0) {
            SaveDealerList(dealerInfoList, area);
        }
    }


    private void SaveDealerList(List<ViDealerInfo> dealerList, String area) {

        try {
            viDealerInfoService.insertByBatch(dealerList, area);
        } catch (Exception e) {
            e.printStackTrace();

            for (ViDealerInfo vd : dealerList) {
                try {
                    viDealerInfoService.save(vd);
                } catch (Exception ex) {
                    System.out.println("has exist! " + vd.getDealerid());
                }
            }
        }
    }



    private void GetAreaInfo(String area) {
        System.out.println("get data from " + area + " db start...");

//        List<FxDealerinfo> dealers = null;
        List<FxAreainfo> areainfoList = null;

        try {
            // 鍒囨崲鏁版嵁搴
            Helper.changeDB(area);

            areainfoList = fxAreainfoService.findList(new FxAreainfo());
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        Collections.sort(areainfoList, new Comparator<FxAreainfo>() {
            @Override
            public int compare(FxAreainfo o1, FxAreainfo o2) {
                return  Integer.valueOf(o1.getAreacode().length()).compareTo(o2.getAreacode().length());
            }
        });

        for (FxAreainfo fai: areainfoList) {
            VivoArea oldA = vivoAreaService.get(fai.getAreaid());
            System.out.println(fai.getAreaid());
            System.out.println(fai.getAreacode());
            if (oldA != null) {
                System.out.println("has exist!");
                continue;
            }

            VivoArea varea = new VivoArea();
            varea.setIsTaskInsert(true);
            varea.setId(fai.getAreaid());
            varea.setCode(fai.getAreacode());
            varea.setLevelId(fai.getArealevelid());
            varea.setStateId(fai.getAreastateid());
            varea.setName(fai.getAreaname());

            if (fai.getParentareaid() == null) {
                varea.setParent(null);
            } else {
                VivoArea parArea = vivoAreaService.get(fai.getParentareaid());
                if (parArea != null) {
                    varea.setParent(parArea);
                } else {
                    varea.setParent(null);
                }
            }

            vivoAreaService.save(varea);
        }

        System.out.println("get data from " + area + " db end.");
    }


    private void GetDealerRelation(String area) {
        System.out.println("get data from " + area + " db start...");

        List<FxDealerrelation> relationList = null;

        try {
            // 删除所有数据
            VivoDealerRelation vdr = new VivoDealerRelation();
            vdr.setTableZone(area);
            vivoDealerRelationService.deleteAll(vdr);

            // 鍒囨崲鏁版嵁搴
            Helper.changeDB(area);

            relationList = fxDealerrelationService.findList(new FxDealerrelation());
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        Collections.sort(relationList, new Comparator<FxDealerrelation>() {
            @Override
            public int compare(FxDealerrelation o1, FxDealerrelation o2) {
                return Integer.valueOf(o1.getLevelcode().length()).compareTo(o2.getLevelcode().length());
            }
        });

        saveDealerRelationList(relationList, area);

        System.out.println("get data from " + area + " db end.");
    }


    private void saveDealerRelationList(List<FxDealerrelation> relations, String area) {
        for (FxDealerrelation relation: relations) {
            VivoDealerRelation vdr = new VivoDealerRelation();
            vdr.setTableZone(area);
            vdr.setIsTaskInsert(true);
            vdr.setId(relation.getDealerrelationid());
            vdr.setCode(relation.getLevelcode());
            vdr.setDepth(relation.getLeveldepth());
            vdr.setIsClose(relation.getIsclosed());
            vdr.setCloseDate(relation.getCreateDate());
            vdr.setCloseUserName(relation.getCloseusername());
            vdr.setShowOrderCode(relation.getShowordercode());
            vdr.setCloseReason(relation.getClosereason());
            vdr.setDealerId(relation.getDealerid());
            vdr.setParentDealerId(relation.getParentdealerid());

            if (relation.getParentdealerrelationid() == null) {
                vdr.setParent(null);
            } else {
                VivoDealerRelation parent = new VivoDealerRelation();
                parent.setTableZone(area);
                parent.setId(relation.getParentdealerrelationid());

                vdr.setParent(parent);

                VivoDealerRelation praVdr = vivoDealerRelationService.getPE(vdr);
                if (praVdr != null) {
                    vdr.setParent(praVdr);
                } else {
                    vdr.setParent(null);
                }
            }

            try
            {
                vivoDealerRelationService.save(vdr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Autowired
    private ViAgenterWithLevelService viAgenterWithLevelService;

    private void getAgenterInfo(String area) {
        System.out.println("get agent data from " + area + " db start...");

        List<ViAgenterWithLevel> fxAgentList = null;

        try {
            Helper.changeDB(area);
            fxAgentList = viAgenterWithLevelService.findListExt();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        // 保存信息
        saveAgenter(fxAgentList, area);

        System.out.println("get agent data from " + area + " db end!");
    }


    private void saveAgenter(List<ViAgenterWithLevel> agenterList, String area) {
        // 删除数据库信息
        ViAgenterWithLevel tempAgent = new ViAgenterWithLevel();
        tempAgent.setTableZone(area);
        viAgenterWithLevelService.deleteAll(tempAgent);

        for (ViAgenterWithLevel agenter: agenterList) {
            agenter.setTableZone(area);

            viAgenterWithLevelService.save(agenter);
        }
    }


    @Autowired
    private ViAgenterTerminalService viAgenterTerminalService;

    private void getAgenterTerminal(String area) {
        System.out.println("get agent terminal data from " + area + " db start...");

        List<ViAgenterTerminal> fxTerminalList = null;

        try {
            Helper.changeDB(area);
            fxTerminalList = viAgenterTerminalService.findListExt();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        // 保存信息
        saveAgenterTerminal(fxTerminalList, area);

        System.out.println("get agent terminal data from " + area + " db end!");
    }

    private void saveAgenterTerminal(List<ViAgenterTerminal> terminalList, String area) {
        ViAgenterTerminal tempT = new ViAgenterTerminal();
        tempT.setTableZone(area);
        viAgenterTerminalService.deleteAll(tempT);

        int pageSize = 1000;
        int size = terminalList.size();

        if (pageSize < size) {
            int part = size / pageSize; // batch count

            for (int i = 0; i < part; i++) {
                saveAgenterTList(terminalList.subList(0, pageSize), area);

                // 剔除
                terminalList.subList(0, pageSize).clear();
            }

            if (!terminalList.isEmpty()) {
                saveAgenterTList(terminalList, area);
            }
        } else {
            saveAgenterTList(terminalList, area);
        }
    }

    private void saveAgenterTList(List<ViAgenterTerminal> list, String area) {
        try {
            viAgenterTerminalService.insertByBatch(list, area);
        } catch (Exception e) {
            e.printStackTrace();

            for (ViAgenterTerminal agenterTerminal : list) {
                agenterTerminal.setTableZone(area);
                try {
                    viAgenterTerminalService.save(agenterTerminal);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    @Autowired
    private VivoWarehouseService vivoWarehouseService;

    @Autowired
    private FxWarehouseinfoService fxWarehouseinfoService;


    public void SyncWarehouseInfo() {
        GetWarehouseInfo("ah");
        GetWarehouseInfo("js");
    }

    private void GetWarehouseInfo(String area) {
        System.out.println("get warehouse info data from " + area + " db start...");

        List<FxWarehouseinfo> houseList = null;

        int pageStart = 1;
        int pageSize = 5000;
        Page<FxWarehouseinfo> page = new Page<FxWarehouseinfo>(pageStart, pageSize);
        FxWarehouseinfo fxWarehouseinfo = new FxWarehouseinfo();

        VivoWarehouse vivoWarehouse = new VivoWarehouse();
        vivoWarehouse.setTableZone(area);

        // 清空数据库
        vivoWarehouseService.deleteAll(vivoWarehouse);

        try {
            // 切换数据库
            Helper.changeDB(area);

            Page<FxWarehouseinfo> pageRes = fxWarehouseinfoService.findPage(page, fxWarehouseinfo);
            DatabaseContextHolder.setMainDb();

            saveWarehouseinfo(pageRes.getList(), area);

            for (int i = pageStart + 1; i <= pageRes.getTotalPage(); i++) {
                System.out.println("page count is : " + pageRes.getTotalPage() + " page num is " + pageRes.getPageNo());
                page.setPageNo(i);

                Helper.changeDB(area);

                pageRes = fxWarehouseinfoService.findPage(page, fxWarehouseinfo);
                DatabaseContextHolder.setMainDb();

                saveWarehouseinfo(pageRes.getList(), area);
            }
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        System.out.println("get data from " + area + " db end.");
    }

    private void saveWarehouseinfo(List<FxWarehouseinfo> warehouseinfos, String area) {
        List<VivoWarehouse> warehouseList = new ArrayList<VivoWarehouse>();
        Date timeNow = new Date();

        for (FxWarehouseinfo fwi: warehouseinfos) {
            VivoWarehouse vwh = new VivoWarehouse();
            vwh.setId(IdGen.uuid());
            vwh.setCreateDate(timeNow);
            vwh.setUpdateDate(timeNow);

            vwh.setTableZone(area);
            vwh.setWarehouseId(fwi.getWarehouseid());

            vwh.setName(fwi.getWarehousename());
            vwh.setDealerId(fwi.getWarehousedealerid());
            vwh.setMatDealerId(fwi.getMatdealerid());
            vwh.setCode(fwi.getWarehousecode());
            vwh.setType(fwi.getWarehousetype());
            vwh.setProperty(fwi.getWarehouseproperty());
            vwh.setRemarks(fwi.getRemarks());
            vwh.setDefaultType(fwi.getDefaultwarehousetype());
            vwh.setLevel(fwi.getWarehouselevel());

            try {
                vivoWarehouseService.save(vwh);
            } catch (Exception e) {
                List<VivoWarehouse> list = vivoWarehouseService.findList(vwh);
                if (list.size() > 0) {
                    System.out.println("has existed ..." + vwh.getWarehouseId());
                    continue;
                }
            }

            warehouseList.add(vwh);

            if (warehouseList.size() >= 1000) {
                SaveWarehouseList(warehouseList, area);

                warehouseList.clear();
            }
        }

        if (warehouseList.size() > 0) {
            SaveWarehouseList(warehouseList, area);
        }
    }


    /**
     * 批量保存数据， 失败则单条插入数据
     * @param warehouseList
     * @param area
     */
    private void SaveWarehouseList(List<VivoWarehouse> warehouseList, String area) {
        try {
            vivoWarehouseService.insertByBatch(warehouseList, area);
        } catch (Exception e) {
            e.printStackTrace();

            for (VivoWarehouse warehouse : warehouseList) {
                try {
                    vivoWarehouseService.save(warehouse);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
